import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    allTabs: [],
    userName: "",
    userAccount: "",
  },
  getters: {
    getAllTabs: (state) => {// 查询有哪些tab
      return state.allTabs
    },
    getActiveTab: (state) => {// 当前那个是激活状态的tab
      let activeList = state.allTabs.map(item => {
        return item.isActive
      })
      if (activeList.indexOf(true) > -1) {
        return state.allTabs[activeList.indexOf(true)].id
      } else {
        return "-1"
      }
    }
  },
  mutations: {
    setAccount(state, payload) {
      state.userAccount = payload;
    },
    pushTab(state, payload) {// 在后面追加一个tab：新追加的是激活状态，其他都是非激活状态
      state.allTabs.forEach(item => {
        item.isActive = false;
      })
      state.allTabs.push({
        isActive: true,
        ...payload
      })
    },
    activeTab(state, payload) {// 激活某个tab
      state.allTabs.forEach(item => {
        if (item.id == payload.id) {
          item.isActive = true;
        } else {
          item.isActive = false;
        }
      })
    },
    deleteTab(state, payload) {// 根据id关闭某个tab：如果这个tab不是激活状态，啥也不用管；如果是激活状态，要设置下一个谁激活
      let currTabIndex = state.allTabs.map(item => {
        return item.id
      }).indexOf(payload)
      if (currTabIndex > -1 && state.allTabs[currTabIndex].isActive && state.allTabs.length >= 2) {
        state.allTabs[currTabIndex].isActive = false;
        if (currTabIndex == 0) {
          state.allTabs[currTabIndex + 1].isActive = true;
        } else {
          state.allTabs[currTabIndex - 1].isActive = true;
        }
      }
      state.allTabs = state.allTabs.filter(item => {
        return item.id != payload
      })
    },
    clearTab(state) {
      state.allTabs = [];
    },
  },
  actions: {},
  modules: {}
})
